package whf.framework.meta.entity;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import whf.framework.entity.AbstractEntity;
import whf.framework.util.StringUtils;

/**
 * @author wanghaifeng
 *
 */
public abstract class AbstractMeta<PT extends IProperty> extends AbstractEntity implements IMeta<PT>{
	private String reportTemplate;
	
	private String helpContent;
	
	private Set<PT> properties = new TreeSet<PT>();
	
	public final void addProperty(PT property){
		if(property == null) return;
		if(property.getName() == null || this.existsProperty(property.getName())){
//			log.info(Messages.getString("exception.property_already_exists", new Object[]{property.getName(), this.getName()}));
			return;
		}
		if(property instanceof IProperty){
			this.properties.add(property);
		}
	}

	public Set<PT> getProperties() {
		return this.properties;
	}
	
	public void setProperties(Set<PT> objectProperties) {
		this.properties = objectProperties;
	}

	public final boolean existsProperty(PT bp) {
		if(bp == null) return false;
		return this.properties.contains(bp);
	}

	public final boolean existsProperty(String propName) {
		for(IProperty bp: this.properties){
			if(StringUtils.equalsIgnoreCase(propName, bp.getName())){
				return true;
			}
		}
		return false;
	}

	public PT findProperty(String propName) {
		for(PT bp: this.properties){
			if(StringUtils.equalsIgnoreCase(propName, bp.getName())){
				return bp;
			}
		}
		return null;
	}
	
	public List<PT> getSortedProperties(){
		List<PT> list = new ArrayList<PT>();
		list.addAll(properties);
		Collections.sort(list, new PropertyComparator<PT>());
		return list;
	}
	
	class PropertyComparator<T> implements Comparator<PT> {
		public int compare(IProperty o1, IProperty o2) {
			return o1.getSortOrder() - o2.getSortOrder();
		}
	}

	/**
	 * @return the reportTemplate
	 */
	public String getReportTemplate() {
		return reportTemplate;
	}

	/**
	 * @param reportTemplate the reportTemplate to set
	 */
	public void setReportTemplate(String reportTemplate) {
		this.reportTemplate = reportTemplate;
	}

	public String getHelpContent() {
		return helpContent;
	}

	public void setHelpContent(String helpContent) {
		this.helpContent = helpContent;
	}
}
